<?php
/**
 * Geneone: Content Management Framework
 * General Class
 *
 * http://geneone.neondragon.net/
 *
 * @package Geneone
 * @author Khlo
 * @version 1.0
 * @copyright 2004-2006 Geneone Development Team
 */
 
// Load required PEAR classes
require_once ("PEAR.php");
require_once ("MDB2.php");
require_once ("Auth.php");
	 
require_once ("Gene/Session.php");
require_once ("Gene/Auth.php");
require_once ("Gene/User.php");

class Gene {
	/**
	 * @var array Gene Settings
	 */
	var $settings;
	
	/**
	 * Class Constructor.
	 *
	 * @var array $config Configuration Settings.
	 */
	function Gene($config) {
		$this->settings =& $config;
	}
	
	/**
	 * Returns a configuration setting without needing to global a var.
	 *
	 * Gene::getSetting("settingname")
	 *
	 * @static
	 * @var string $setting Setting Name
	 * @var string $var Gene Object Name
	 */
	function getSetting($setting, $var="gene") {
		return $GLOBALS[$var]->settings[$setting];
	}
	
	/**
	 * Initializes and returns templating engine.
	 *
	 * @static
	 *
	 * @var array $options Options
	 *
	 * @return object Instance of Gene_Template
	 */
	function &getTemplate($options=array()) {
		static $tpl = null;
		
		if ($tpl === null) {
			require_once 'Gene/Template.php';
			$tpl = new Gene_Template;
			$tpl->templateDir = $options['template_dir'];
			
			$tpl->assign ("application", array(
				"name" => GENE_APPNAME,
				"homepage" => GENE_APPHOMEPAGE,
				"guid" => GENE_APPGUID,
				"version" => GENE_APPVERSION,
				"agent" => GENE_APPAGENT,
			));

			$tpl->assign ("gene_uri", Gene::getSetting("gene_uri"));
			$tpl->assign ("gene_name", Gene::getSetting("gene_name"));
			$tpl->assign ("ui", Gene::getSetting("ui_urls"));
			
			$tpl->assign ("stylesheets", array("common"));
			$tpl->assign ("scripts", array("prototype", "global"));
			
			$tpl->assign ("portlets", array("navigation"));
			$tpl->assign ("textportlets", array());
			
			require_once $tpl->templateDir.'config.php';
			$tpl->assign ("config", $tpl_conf);
			
			require_once $tpl->templateDir.'functions.php';
		}
		
		return $tpl;
	}
	
	/**
	 * Gets a database connection.
	 *
	 * @static
	 * @var string $dsn Database DSN (Data Source Name)
	 * @var array $options Database Options
	 * @var int $fetchmode Database Fetch Mode
	 * @return object Instance of PEAR::MDB2
	 */
	function &getDatabase($dsn="", $options=array(), $fetchmode=MDB2_FETCHMODE_ASSOC) {
		static $dbc = array();
		
		if (!$dsn) {
			$dsn = Gene::getSetting("sql_dsn");
		}
		
		$dsnhash = md5($dsn);

		if (!isset($dbc[$dsnhash])) {
			$dbc[$dsnhash] =& MDB2::connect($dsn, $options);
			if (PEAR::isError($dbc[$dsnhash])) {
				Gene::fatalError("Could not connect to database. Please check your configuration settings.");
			}
		
			$dbc[$dsnhash]->setFetchMode($fetchmode);
			$dbc[$dsnhash]->loadModule('Extended');
		}
		
		return $dbc[$dsnhash];
	}
	
	/**
	 * Get a new PEAR::Auth object.
	 *
	 * @static
	 * @var bool $sesshandler Whether to modify session handler settings
	 * @return object Instance of PEAR::Auth
	 */
	function &getAuth($sesshandler=true) {
		static $auth = null;
		
		if ($auth === null) {
			// Set up Gene Session Handler
			if ($sesshandler) {
				session_set_save_handler(
					array("Gene_Session", "open"),
					array("Gene_Session", "close"),
					array("Gene_Session", "read"),
					array("Gene_Session", "write"),
					array("Gene_Session", "destroy"),
					array("Gene_Session", "gc")
				);
			}
			
			$auth = new Gene_Auth("MDB2", array("dsn" => Gene::getSetting("sql_dsn"), "table" => Gene::tableName("users"), "usernamecol" => "user_id", "passwordcol" => "password", "db_fields" => "*"), "", false);
			//$auth->setAdvancedSecurity(true);
			$auth->setIdle(Gene::getSetting("sess_idle") * 60);
		}
		
		return $auth;
	}
	
	/**
	 * Get a Gene_User object for currently logged in user.
	 *
	 * @static
	 * @return object Instance of Gene_User
	 */
	function &getUser() {
		static $user = null;
		
		if ($user === null) {
			$auth = Gene::getAuth();
			$user = $auth->getUser();
		}
		
		return $user;
	}
	
	/**
	 * Sends an email.
	 *
	 * @static
	 * @var string $to E-Mail Address
	 * @var string $subject E-Mail Subject
	 * @var string $body E-Mail Body
	 * @var array $headers Additional Headers
	 * @return bool Success
	 */
	function sendEmail($to, $subject, $body, $headers=array()) {
		require_once ("Mail.php");
		$settings = Gene::getSetting("email");
		$mail = Mail::factory($settings['backend'], $settings['params']);
		
		$autoheaders = array(
			"From" => $settings['from'],
			"Subject" => $subject,
			"X-Remote-Addr" => $_SERVER['REMOTE_ADDR'],
			"X-Send-Time" => date("r"),
		);
		
		$headers = array_merge($autoheaders, $headers);

		$body .= "\r\n------\r\nThis email was sent from ".Gene::getSetting("gene_name")." at ".date("r")."\r\nIP Address: ".$_SERVER['REMOTE_ADDR'];
		
		$db =& Gene::getDatabase();
		$db->extended->autoExecute(
			Gene::tableName("email_log"),
			array(
				"to_address" => $to,
				"subject" => $subject,
				"body" => $body,
				"timestamp" => time(),
				"ip" => $_SERVER['REMOTE_ADDR'],
			),
			MDB2_AUTOQUERY_INSERT
		);
		
		return $mail->send($to, $headers, $body);
	}
	
	/**
	 * Creates a new HTTP Request Object.
	 *
	 * @return HTTP_Request
	 */
	function &getHttpRequest($url) {
		require_once ("HTTP/Request.php");
		
		$req =& new HTTP_Request($url);
		$req->addHeader("User-Agent", GENE_APPAGENT);
		
		return $req;
	}
	
	/**
	 * Generates a public URL for a given object or page.
	 *
	 * @param string $page Object ID or Alias, or class based on Gene_Object_Model
	 * @param boolean $xml Return URL to XML export of page
	 *
	 * @return string URL to page
	 */
	function makeLink($page, $xml=false) {
		// All objects passed must be extended from GeneObject
		
		if ($xml) {
			$base = Gene::getSetting("xml_uri");
		} else {
			$base = Gene::getSetting("public_uri");
		}
		
		if (is_object($page)) {
			$info = $page->get();
			if ($info['alias']) {
				$url = sprintf($base, $info['alias']);
			} else {
				$url = sprintf($base, $info['object_id']);
			}
		} else if (is_array($page)) {
			if ($page['alias']) {
				$url = sprintf($base, $page['alias']);
			} else {
				$url = sprintf($base, $page['object_id']);
			}
		} else {
			$url = sprintf($base, $page);
		}
		
		return str_replace (array("\n", "\r"), "", $url);
	}
	
	/**
	 * Generates a public URL for the XML export of a given object or page.
	 *
	 * @param string $page Object ID or Alias, or class based on Gene_Object_Model
	 *
	 * @return string URL to XML export page
	 */
	function xmlLink($page) {
		return Gene::makeLink($page, true);
	}
	
	/**
	 * Generates a page ID for a Object Page.
	 *
	 * @param string $id Object Page ID
	 * @return string Full ID of Object Page
	 */
	function objectID($id="") {
		return $id;
	}
	
	/**
	 * Generates a page ID for a Special Page.
	 *
	 * @param string $id Special Page ID
	 * @return string Full ID of Special Page
	 */
	function specialID($id="") {
		return Gene::getSetting("special_prefix").":".$id;
	}
	
	/**
	 * Generates a page ID for a User Page.
	 *
	 * @param string $id Public Name
	 * @return string Full ID of User Page
	 */
	function userID($id="") {
		return Gene::getSetting("user_prefix").":".str_replace(" ", "_", $id);
		
	}
	
	/**
	 * Generates a page ID for a Meta Page.
	 *
	 * @param string $id Metasite Page ID
	 * @return string Full ID of User Page
	 */
	function metaID($id="") {
		return Gene::getSetting("meta_prefix").":".$id;
	}
	
	/**
	 * Generates a page ID for a File.
	 *
	 * @param string $id File ID
	 * @return string Full ID of User Page
	 */
	function fileID($id="") {
		return Gene::getSetting("file_prefix").":".$id;
	}
	
	/**
	 * Gets the table name.
	 *
	 * Prefixes the table id with the prefix used. Can be modified to change the table name
	 * altogether if desired.
	 *
	 * @param string $tableid Table ID
	 * @return string Table Name
	 */
	function tableName($tableid) {
		/* Check for override */
		$override = Gene::getSetting("database_override");
		if(isset($override[$tableid])) {
			return $override[$tableid];
		}
			
		return Gene::getSetting("database_prefix").$tableid;
	}
	
	/**
	 * Displays a fatal error message and exits.
	 *
	 * @var string $message Error Message
	 */
	function fatalError($message) {
		echo '<h1>We apologise for any inconvenience...</h1><p>'.$message.'</p><p><strong>Time:</strong> '.date("r").'</p>';
		exit();
	}
}
 
?>